package luahelper

import (
	"fmt"
	"github.com/google/uuid"
	lua "github.com/yuin/gopher-lua"
	"log"
)

var All_RegisterFunc func(*lua.LState)

func RegisterFunc_4lua(l *lua.LState) {
	luaTable := l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"DofileInNewState": DofileInNewState_4lua,
	})

	l.SetGlobal("Lua", luaTable)
}

func DofileInNewState_4lua(l *lua.LState) int {
	defer func() {
		if err, ok := recover().(error); ok {
			fmt.Printf("DofileInNewState error", err.Error())
		}
	}()

	file := l.ToString(1)
	table := l.ToTable(2)

	nl := lua.NewState()

	if All_RegisterFunc != nil {
		All_RegisterFunc(nl)
	}

	if table != nil {
		l.ForEach(table, func(key lua.LValue, value lua.LValue) {
			nl.SetGlobal(lua.LVAsString(key), value)
		})
	}

	err := nl.DoFile(file)
	if err != nil {
		log.Println(err.Error())

		return PushErrorMessage(l, err.Error())
	}

	return PushStatus(l, true)
}

func RegisterLuaCallback(l *lua.LState, functionName string, function *lua.LFunction) (publicName string) {
	fcId := uuid.New().String()
	fName := fmt.Sprintf("%s_%s", functionName, fcId)
	l.SetGlobal(fName, function)
	return fName
}

func SafeCallLuaCallback(l *lua.LState, publicName string, items ...lua.LValue) {
	defer func() {
		if err, ok := recover().(error); ok {
			fmt.Println("SafeCallBack "+publicName+" Error", err.Error())
		}
	}()

	println("SafeCallLuaCallback", publicName)

	fc := l.GetGlobal(publicName)
	if fc != nil {
		if lfc, ok := fc.(*lua.LFunction); ok {
			l.CallByParam(lua.P{
				Fn:      lfc,
				NRet:    0,
				Protect: false,
				Handler: nil,
			}, items...)
		} else {
			fmt.Printf("尝试调用 %s 时出错, 转换失败\r\n", publicName)
		}
	} else {
		fmt.Printf("尝试调用 %s 时出错, 找不到函数\r\n", publicName)
	}
}
